package javaMSCRM;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.Border;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;
/**
 * @author Zoran IVANOV
 *
 */
public class Settings implements ActionListener
{
   	JFrame appFrame;
   	JTextField hostJTF, portJTF, domainJTF, organizationJTF;
   	JComboBox recordsPerPageJTF;
   	JButton SaveButton;
   	private String host = "";
   	private String port = "";
   	private String domain = "";
   	private String organization = "";
   	private String endpointURL = "";
   	private String recordsPerPage = "50";
   	
   	public String getRecordsPerPage() {
		return recordsPerPage;
	}

	public String getHost(){
   		return host;
   	}
   	
   	public String getPort(){
   		if(port.equals(""))
   			return "0";
   		else
   			return port;
   	}
   	
   	public String getDomain(){
   		return domain;
   	}
   	
   	public String getOrganization(){
   		return organization;
   	}
   	
 	public String getEndpointURL(){
   		return endpointURL;
   	}
   	
   	public File getSettingsFile(){
   		File f;
        f=new File("JavaMSCRMSettings.inc");
        if(!f.exists()){
	        try {
	        	f.createNewFile();
	        } catch (IOException e1) {
	        	JOptionPane.showMessageDialog(null, "Cannot create Settings File!");
	        }
        }
        return f;
   	}

   public Settings()
   {
	    //get info from settings file
	    File f = getSettingsFile();
  
        try{
        	BufferedReader input =  new BufferedReader(new FileReader(f));
			String line = null;
			while (( line = input.readLine()) != null){
				String[] lineArray = line.split("=");
			
				if(lineArray[0].equals("host")){
					host = lineArray[1];
				}else if(lineArray[0].equals("port")){
					port = lineArray[1];
				}else if(lineArray[0].equals("domain")){
					domain = lineArray[1];
				}else if(lineArray[0].equals("organization")){
				    organization = lineArray[1];
				}else if(lineArray[0].equals("endpointURL")){
					endpointURL = lineArray[1];
				}else if(lineArray[0].equals("recordsPerPage")){
					recordsPerPage = lineArray[1];
				}
			}
				
            input.close();
        } catch (IOException e1) {
        	JOptionPane.showMessageDialog(null, "Cannot read from Settings File!");
        }
   }
   
   public Settings(Boolean ShowGUI)
   {
	    //get info from settings file
	    File f = getSettingsFile();
  
        try{
        	BufferedReader input =  new BufferedReader(new FileReader(f));
			String line = null;
			while (( line = input.readLine()) != null){
				String[] lineArray = line.split("=");
			
				if(lineArray[0].equals("host")){
					host = lineArray[1];
				}else if(lineArray[0].equals("port")){
					port = lineArray[1];
				}else if(lineArray[0].equals("domain")){
					domain = lineArray[1];
				}else if(lineArray[0].equals("organization")){
				    organization = lineArray[1];
				}else if(lineArray[0].equals("endpointURL")){
					endpointURL = lineArray[1];
				}else if(lineArray[0].equals("recordsPerPage")){
					recordsPerPage = lineArray[1];
				}
			}
 
            input.close();
        } catch (IOException e1) {
        	JOptionPane.showMessageDialog(null, "Cannot read from Settings File!");
        }
        //Create Settings Windows   
        appFrame = new JFrame("Java MSCRM Settings");
		Image img = Toolkit.getDefaultToolkit().getImage("C:/Users/Zoran/workspace/JavaMSCRM/src/icon.png");
		appFrame.setIconImage(img);		
		JPanel buttonsBar = new JPanel();	
		buttonsBar.setLayout(new FlowLayout(FlowLayout.LEFT));
		Border blackline = BorderFactory.createMatteBorder(1, 0, 1, 0, Color.gray);
		buttonsBar.setBorder(blackline);
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		
		SaveButton = new JButton("Save");
		SaveButton.setPreferredSize(new Dimension(70, 20));
		SaveButton.addActionListener(this);
		buttonsBar.add(SaveButton);
		appFrame.add(buttonsBar, BorderLayout.NORTH);
		appFrame.add(FormScrollPane, BorderLayout.CENTER);
		appFrame.pack();
		appFrame.setVisible(true);
   }

   	private JPanel setupFields(){
		LC layC = new LC().wrap();
		AC colC = new AC().align("right", 0).fill(1, 3).grow(100, 1, 3).align("right", 2).gap("15", 1);
		AC rowC = new AC().index(6).gap("15!").align("top").grow(100, 0);	
		JPanel form = new JPanel(new MigLayout(layC, colC, rowC));		
		JPanel formContainer = new JPanel(new MigLayout(layC, colC, rowC));		
		formContainer.add(form, BorderLayout.NORTH);			
		form.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		//Create TextFields
		try{hostJTF = new JTextField(host);}catch (Exception e) {}
		try{portJTF = new JTextField(port);}catch (Exception e) {}
		try{domainJTF = new JTextField(domain);}catch (Exception e) {}
		try{organizationJTF = new JTextField(organization);}catch (Exception e) {}
		
		recordsPerPageJTF = new JComboBox();
   		recordsPerPageJTF.addItem("50");
   		recordsPerPageJTF.addItem("100");
   		recordsPerPageJTF.addItem("500");
   		recordsPerPageJTF.addItem("1000");
   		recordsPerPageJTF.setSelectedItem(recordsPerPage);
		
		form.add(new JLabel("Host:"));		
		form.add(hostJTF, "w 200:100:");
		form.add(new JLabel("Port:"));
		form.add(portJTF, "w 200::");
		form.add(new JLabel("Domain:"));		
		form.add(domainJTF, "w 200:100:");
		form.add(new JLabel("Organization:"));		
		form.add(organizationJTF, "w 200:100:");
		form.add(new JLabel("Records / page:"));		
		form.add(recordsPerPageJTF, "w 200:100:");
		
		return formContainer;
	}
   
   	public void actionPerformed (ActionEvent e){   		
   		if (e.getSource () == SaveButton){
   			saveSettings();
        }
   	}
   	
     // Save Settings
     public void saveSettings(){ 
	   	host = hostJTF.getText();
	   	port = portJTF.getText();
	   	domain = domainJTF.getText();
	   	organization = organizationJTF.getText();
	   	recordsPerPage = recordsPerPageJTF.getSelectedItem().toString();

	   	if(host.equals("") || port.equals("") || domain.equals("") || organization.equals("")){
	   		JOptionPane.showMessageDialog(null, "All fields Are Mandatory.");
	   	}else{
	   		File f = getSettingsFile();
	   		
	        try{
	        	Writer output = null;
	    		output = new BufferedWriter(new FileWriter(f));
	    	    output.write("host="+host+"\r\nport="+port+"\r\ndomain="+domain+"\r\norganization="+organization+"\r\nrecordsPerPage="+recordsPerPage+"\r\nendpointURL=http://"+host+"/MSCrmServices/2007/CrmService.asmx");
	    	    output.close();
	    	    JOptionPane.showMessageDialog(null, "JavaMSCRM must close to apply the new settings.");
	    	    System.exit(0);
	        } catch (IOException e1) {
	        	JOptionPane.showMessageDialog(null, "Cannot write into Settings File!");
	        }		   	
	    }
     }
   }